package com.cnfilm.common;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.cnfilm.gather.GatherBean;
import com.cnfilm.gather.GatherURL;
import com.cnfilm.utils.DateUtils;
import com.cnfilm.utils.ReadPropertity;
import com.cnfilm.utils.StringUtils;

/**
 * 影片信息采集工具
 * @author john
 * @date 2013-08-31
 */
public class GatherUtil {
	
	private static final String BASE_URL = "http://hao.uoso.net"; 
	
	/**
	 * 查询影片数据[查询所有分类数据]
	 * @return
	 * @throws IOException
	 */
	public static List<GatherBean> getGatherList() throws IOException{
		List<GatherBean> gatherBeanList = new ArrayList<GatherBean>();
		for(GatherURL c : GatherURL.values()) { 
			gatherBeanList.addAll(getGatherList(c.getUrl(),c.getType()));
        }  
		List<GatherBean> newGatherBeanList = new ArrayList<GatherBean>();
		for(GatherBean gather:gatherBeanList){
			gather = getGatherInfo(gather);
			if(gather!=null){
				newGatherBeanList.add(gather);
			}
		}
		return newGatherBeanList;
	}
	
	/**
	 * 根据分类查询数据
	 * @param url
	 * @param type
	 * @return
	 * @throws IOException
	 */
	public static List<GatherBean> getGatherList(String url,String type) throws IOException{
		String date = DateUtils.getNowTime(DateUtils.DATE_SMALL_STR);
		List<GatherBean> gatherList = new ArrayList<GatherBean>();
		/**查找网页中列表数据**/
		Document doc = Jsoup.connect(url).timeout(60000).get(); 

        GatherBean gatherBean = null;
        Elements tdElements = doc.getElementsByClass("l");
        Elements fontElements = doc.getElementsByClass("DianDian");
        
        Element fontElement = null;
        for(int i=0;i<tdElements.size();i++){
        	fontElement = fontElements.get(i).getElementsByTag("font").get(2);
        	if(fontElement.html().contains(date)){
        		gatherBean = new GatherBean();
        		url = BASE_URL + tdElements.get(i).getElementsByTag("a").get(0).attr("href");
        		gatherBean.setUrl(url);
        		gatherBean.setType(type);
        		gatherBean.setDate(date);
        		gatherList.add(gatherBean);
        	}
        }
		return gatherList;
	}
	
	/**
	 * 查询采集详情
	 * @param gatherBean
	 * @return
	 * @throws IOException 
	 */
	public static GatherBean getGatherInfo(GatherBean gatherBean) throws IOException{
		String url = gatherBean.getUrl();
		try{
			Document doc = Jsoup.connect(url).timeout(60000).get(); 
			String html = doc.html();
			int beginIndex = html.indexOf("<!--片名开始-->");
			int endIndex = html.indexOf("<!--片名结束-->");
			String name = html.substring(beginIndex+11, endIndex).replace("\n", "").trim();
			gatherBean.setName(name);
			
			beginIndex = html.lastIndexOf("<!--主演开始-->");
			endIndex = html.lastIndexOf("<!--主演结束-->");
			String actor = html.substring(beginIndex+11, endIndex).replace(",", "、").trim();
			gatherBean.setActor(actor);
			
			beginIndex = html.indexOf("<!--年代开始-->");
			endIndex = html.indexOf("<!--年代结束-->");
			String sytime = html.substring(beginIndex+11, endIndex).trim();
			gatherBean.setSytime(sytime);
			
			beginIndex = html.indexOf("<!--栏目开始-->");
			endIndex = html.indexOf("<!--栏目结束-->");
			String tags = html.substring(beginIndex+11, endIndex).trim();
			gatherBean.setTags(tags);
			
			beginIndex = html.indexOf("<!--简介开始-->");
			endIndex = html.indexOf("<!--简介结束-->");
			String juqing = html.substring(beginIndex+11, endIndex).trim();
			gatherBean.setJuqing(juqing);
			
			beginIndex = html.indexOf("<!--地区开始-->");
			endIndex = html.indexOf("<!--地区结束-->");
			String area = html.substring(beginIndex+11, endIndex).trim();
			gatherBean.setArea(area);
			
			String img = doc.getElementsByClass("videoPic").get(0).child(0).attr("src");
			gatherBean.setImg(downImg(img));
			
        	return gatherBean;
		}catch(Exception e){
			return null;
		}
	}
	
	/**
	 * 
	 * @param url
	 * @return
	 * @throws MalformedURLException 
	 * @throws FileNotFoundException 
	 */
	public static String downImg(String fileUrl) throws Exception{
		String img = "";
		try{
			String fileTime = DateUtils.getNowTime(DateUtils.DATE_KEY_STR);
			String newFileName = fileTime + "."+ StringUtils.getExtensionName(fileUrl);
			URL url = new URL(fileUrl);
			String path = System.getProperty("user.dir") + ReadPropertity.getProperty("actorpic") + newFileName;
			File outFile = new File(path);
			OutputStream os = new FileOutputStream(outFile);
			InputStream is = url.openStream();
			byte[] buff = new byte[1024];
			while(true) {
				int readed = is.read(buff);
				if(readed == -1) {
					break;
				}
				byte[] temp = new byte[readed];
				System.arraycopy(buff, 0, temp, 0, readed);
				os.write(temp);
			}
			is.close(); 
	        os.close();	
	        img = ReadPropertity.getProperty("actorpic") + newFileName;
		}catch(Exception e){
			img = "/images/nopic.gif";
		}	
		return img;
	}
	
	
	
	/**
	 * 测试
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException{ 
		List<GatherBean> gatherBeanList = getGatherList();
		for(GatherBean gather:gatherBeanList){
			System.out.println(gather.getUrl()+"["+gather.getName()+"："+gather.getImg()+"]");
		}
	}

}
